/**
 * 目标1：信息渲染
 *  1.1 获取用户的数据
 *  1.2 回显数据到标签上
 * */
const doms = {
  form: document.querySelector('.user-form'),
  upload: document.querySelector('.upload'),
  submit: document.querySelector('.submit')

}
const creator = '我很专业'
axios({
  url: 'http://hmajax.itheima.net/api/settings',
  method: 'get',
  params: {          //必须加大括号
    creator
  }
}).then(result => {
  // console.log(result)
  // console.log(result.data.data) //obj
  // const { avator, desc, email, gender, nickname } = result.data.data
  // document.querySelector('.nickname').value = nickname
  // document.querySelector('.email').value = email
  // document.querySelectorAll('.gender')[obj[gender]].value = gender       //
  // document.querySelector('.desc').value = desc
  // document.querySelector('.prew').src = avatar

  //当数量多时完全可以遍历对象（Object.keys(obj) => arr => arr.forEach）
  const obj = result.data.data
  // console.log(typeof obj.gender)//number
  Object.keys(obj).forEach(item => {
    if (item === 'avatar') {       //注意avatar 错看成avator了呜呜呜
      document.querySelector('.prew').src = obj[item]
    } else if (item === 'gender') {
      document.querySelectorAll('.gender')[obj[item]].checked = true
    } else {
      document.querySelector(`.${item}`).value = obj[item]
    }

  })
})

// 头像修改
doms.upload.addEventListener('change', e => {
  // console.log(e.target.files[0])
  const fd = new FormData()
  fd.append('avatar', e.target.files[0]) //avatar
  fd.append('creator', creator)//creator
  axios({
    url: 'http://hmajax.itheima.net/api/avatar',
    method: 'put',
    data: fd      //只有fd
  }).then(result => {
    // console.log(result)
    // console.log(result.data.data)
    // 回显
    document.querySelector('.prew').src = result.data.data.avatar
  })
})

// 表单信息修改
doms.submit.addEventListener('click', () => {
  const formObj = serialize(doms.form, {
    hash: true,
    empty: true
  })
  console.log(formObj) //少一个creator
  formObj.creator = creator
  formObj.gender = +formObj.gender //转化为number
  axios({
    url: 'http://hmajax.itheima.net/api/settings',
    method: 'put',
    data: formObj          //data， 对象进入axios自动转化为json字符串
  }).then(result => {
    console.log(result)

    // toast提示
    const tost = document.querySelector('.my-toast')
    const toast = new bootstrap.Toast(tost)
    toast.show()
  })
})
